<!--
 * @Description: 
 * @Author: lwx
 * @Date: 2022-06-14 16:57:21
 * @LastEditors: lwx
 * @LastEditTime: 2022-06-30 14:39:30
-->
<template>
  <div
    :id="id"
    :class="className"
    :style="{ height: height, width: width }"
    ref="echarts"
  />
</template>

<script>
import tdTheme from "./theme.json"; // 引入默认主题
export default {
  name: "echart",
  props: {
    className: {
      type: String,
      default: "chart",
    },
    id: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "2.5rem",
    },
    options: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    options: {
      handler(options) {
        // 设置true清空echart缓存
        this.chart.setOption(options, true);
      },
      deep: true,
    },
  },
  created() {
     window.addEventListener('resize',this.resizeChart)
  },
  mounted() {
    this.$echarts.registerTheme("tdTheme", tdTheme); // 覆盖默认主题
    this.initChart() 
  
  },
  activated() {
      // 防止 keep-alive 之后图表变形
      if (this.chart) {
          this.chart.resize()
      }
  },
  beforeDestroy() {
      window.removeEventListener('reisze', this.resizeChart);
  },
  methods: {
    initChart() {
      // 初始化echart
      this.chart = this.$echarts.init(this.$el, "tdTheme");
      this.chart.setOption(this.options, true);
    }, 
    resizeChart(){
      if(this.chart){
        this.chart.resize()
      }
    }
  },
};
</script>

<style></style>
